<?php

namespace SC\Venus\Support\Middleware;

use Closure;

/**
 * 禁止google索引
 */
class AntiGoogle
{
    public function handle($request, Closure $next)
    {
        if ($this->shouldBan($request)) {
            return response()->view('venus::support.antigoogle', [], 403);
        }
        return $next($request);
    }

    protected function shouldBan ($request) {
        if (\Str::startsWith($request->path(), 'admin')) {
            return false;
        }

        $ua = \strtolower($request->header('User-Agent', ''));
        $lang = \strtolower(substr($request->server('HTTP_ACCEPT_LANGUAGE', ''), 0, 2));

        if (\Str::contains($ua, 'googlebot')) {
            return true;
        }

        if ($lang === 'zh') {
            return false;
        }

        if (\Str::contains($ua, [
            'windows nt', 'iphone', 'ipad', 'android',
            'msie', 'safari', '360se',
            'tencent', 'baidu', 'sogou',
        ])) {
            return false;
        }

        if (\Str::contains($ua, ['spider', 'bot'])) {
            return \Str::contains($ua, 'google');
        }

        return false;
    }
}